﻿#include "NearFieldDataGenerator.h"
#include <vtkTable.h>
#include <vtkDataSet.h>
#include <vtkDoubleArray.h>
#include <vtkPointData.h>
#include <vtkStructuredGrid.h>
#include <vtkTableToStructuredGrid.h>
#include <vtkStructuredGridWriter.h>
#include <unordered_set>
#include <qDebug>
#include <QList>
#include <vtkVariantArray.h>
#include "CommonFunction.h"
#include <vtkDelimitedTextWriter.h>
#include "TextArrayMetaHander.h"

namespace pst
{

    NearFieldDataGenerator::NearFieldDataGenerator(QObject* parent)
        : QObject(parent)
        , m_useLog(false)
        , m_useNormalize(false)
        , m_originalTable(nullptr)
        , m_resultTable(nullptr)
        , m_resultDataSet(vtkSmartPointer<vtkStructuredGrid>::New())
        , m_logFactory(10)
        , m_inverserXYZ{ false }
        , m_isDataExtracted{ false }
        , m_sliceAxis{ -1 }
        , m_sliceValueIndex{ -1 }
        , xSlicePositionUnit{}
        , ySlicePositionUnit{}
        , zSlicePositionUnit{}
    {
    }

    NearFieldDataGenerator::~NearFieldDataGenerator()
    {
    }

    void NearFieldDataGenerator::setInputData(vtkTable* table)
    {
        m_originalTable = table;
    }

    void NearFieldDataGenerator::setLogTheData(bool useLog)
    {
        m_useLog = useLog;
    }

    bool NearFieldDataGenerator::getLogTheData()
    {
        return m_useLog;
    }

    void NearFieldDataGenerator::setNormalizeTheData(bool useNormalize)
    {
        m_useNormalize = useNormalize;
    }

    bool NearFieldDataGenerator::getNormalizeTheData()
    {
        return m_useNormalize;
    }

    void NearFieldDataGenerator::setDataExtraction(int sliceAxis, int slicePositionIndex)
    {
        m_sliceAxis = sliceAxis;
        m_sliceValueIndex = slicePositionIndex;
    }

    void NearFieldDataGenerator::getDataExtraction(int& sliceAxis, int& slicePositionIndex)
    {
        sliceAxis = m_sliceAxis;
        slicePositionIndex = m_sliceValueIndex;
    }

    bool NearFieldDataGenerator::update(int realValueIndex)
    {
        if (m_originalTable == nullptr)
        {
            return false;
        }
        //if (!m_isDataExtracted)
        //{
        m_extractedXTables.clear();
        m_extractedYTables.clear();
        m_extractedZTables.clear();
        m_xList.clear();
        m_yList.clear();
        m_zList.clear();
        extractDataFromTable(m_originalTable, m_xList, m_yList, m_zList,
            m_extractedXTables, m_extractedYTables, m_extractedZTables);
        //    m_isDataExtracted = true;
        //}

        //qDebug() << "m_extractedXTables.size = " << m_extractedXTables.size() << " m_extractedYTables.size = " << m_extractedYTables.size() << " m_extractedZTables.size = " << m_extractedZTables.size();

        //qDebug() << "m_xList = " << m_xList;
        //qDebug() << "m_yList = " << m_yList;
        //qDebug() << "m_zList = " << m_zList;

        //for (int  i = 0; i < m_extractedXTables.size();++i)
        //{
        //    QString name2 = "X" + QString::number(m_xList[i]) + ".txt";
        //    vtkNew<vtkDelimitedTextWriter> writer;
        //    writer->SetInputData(m_extractedXTables[i]);
        //    writer->SetFileName(name2.toStdString().c_str());
        //    writer->Write();
        //}
        //for (auto i = 0; i < m_extractedYTables.size(); ++i)
        //{
        //    QString name2 = "Y" + QString::number(m_yList[i]) + ".csv";
        //    vtkNew<vtkDelimitedTextWriter> writer;
        //    writer->SetInputData(m_extractedYTables[i]);
        //    writer->SetFileName(name2.toStdString().c_str());
        //    writer->Write();
        //}
        //for (auto  i = 0; i < m_extractedZTables.size(); ++i )
        //{
        //    QString name2 = "Z" + QString::number(m_zList[i]) + ".txt";
        //    vtkNew<vtkDelimitedTextWriter> writer;
        //    writer->SetInputData(m_extractedZTables[i]);
        //    writer->SetFileName(name2.toStdString().c_str());
        //    writer->Write();
        //}

        bool isOk = false;
        auto currentTable = extractTable(isOk);
        if (!isOk)
        {
            qDebug() << "Data Extraction Failed";
            return false;
        }
        //qDebug() << "Data Extraction Success";
        //currentTable->Print(std::cout);

        auto sliceEnums = computeTableExtends(currentTable);

        //先归一化
        vtkSmartPointer<vtkTable> normalizedTable;
        if (m_useNormalize)
        {
            normalizedTable = vtkSmartPointer<vtkTable>::New();
            normalizeTheTable(currentTable, normalizedTable);//只处理选择列
        }
        else
        {
            normalizedTable = currentTable;
        }

        //再取对数
        double colorOffeset{ 0 };
        if (m_useLog)
        {
            decideLogCoefficients();

            m_resultTable = vtkSmartPointer<vtkTable>::New();
            logTheTable(normalizedTable, m_resultTable, colorOffeset, realValueIndex);//只处理选择列
        }
        else
        {
            m_resultTable = normalizedTable;
        }

        m_resultDataSet = ConvertTableToStructuredGrid(m_resultTable);
        m_resultDataSet->GetPointData()->SetActiveAttribute(realValueIndex, vtkDataSetAttributes::AttributeTypes::SCALARS);
        return true;
    }

    QList<double> NearFieldDataGenerator::GetXSlicePositionEnum()
    {
        return m_xList;
    }

    QList<double> NearFieldDataGenerator::GetYSlicePositionEnum()
    {
        return m_yList;
    }

    QList<double> NearFieldDataGenerator::GetZSlicePositionEnum()
    {
        return m_zList;
    }

    QString NearFieldDataGenerator::GetXSlicePositionUnit()
    {
        return xSlicePositionUnit;
    }

    QString NearFieldDataGenerator::GetYSlicePositionUnit()
    {
        return ySlicePositionUnit;
    }

    QString NearFieldDataGenerator::GetZSlicePositionUnit()
    {
        return zSlicePositionUnit;
    }

    vtkStructuredGrid* NearFieldDataGenerator::getOutputData()
    {
        return m_resultDataSet;
    }

    //void NearFieldDataGenerator::SetLogCoefficients(double factory)
    //{
    //    m_logFactory = factory;
    //}

    vtkSmartPointer<vtkTable> NearFieldDataGenerator::getResultTable()
    {
        return m_resultTable;
    }

    // 说明：
    // 输入的 vtkTable 必须包含至少 3 列，前 3 列依次为 x, y, z 坐标，其它列为场数据。
    // 函数内部自动提取 x, y, z 的唯一值以确定网格尺寸，然后构造一个 mapping，将原始表格的每一行映射到网格内的 (i, j, k) 位置。
    // 接着按照 X 快速变化、Y 次之、Z 最慢的顺序重排 vtkTable 中的点和相应的场数据，最终返回一个 vtkStructuredGrid 对象。

    vtkSmartPointer<vtkStructuredGrid> NearFieldDataGenerator::ConvertTableToStructuredGrid(vtkTable* table1)
    {
        if (!table1)
        {
            qDebug() << "错误：输入的 table 为空！";
            return nullptr;
        }

        // 检查是否至少包含 3 列
        if (table1->GetNumberOfColumns() < 3)
        {
            qDebug() << "错误：table 至少需要有 3 列（x, y, z 坐标）!";
            return nullptr;
        }

        vtkNew<vtkTable> table;
        table->DeepCopy(table1);
        convertKeyColumnsUnitToMM(table);

        // 假设前 3 列分别为 x, y, z
        vtkAbstractArray* xArray = table->GetColumn(0);
        vtkAbstractArray* yArray = table->GetColumn(1);
        vtkAbstractArray* zArray = table->GetColumn(2);

        vtkIdType nRows = table->GetNumberOfRows();

        // 利用 set 获取 x, y, z 唯一的坐标值（自动排序）
        std::set<double> xSet, ySet, zSet;
        for (vtkIdType r = 0; r < nRows; r++)
        {
            xSet.insert(xArray->GetVariantValue(r).ToDouble());
            ySet.insert(yArray->GetVariantValue(r).ToDouble());
            zSet.insert(zArray->GetVariantValue(r).ToDouble());
        }

        std::vector<double> xUnique(xSet.begin(), xSet.end());
        std::vector<double> yUnique(ySet.begin(), ySet.end());
        std::vector<double> zUnique(zSet.begin(), zSet.end());

        int nX = static_cast<int>(xUnique.size());
        int nY = static_cast<int>(yUnique.size());
        int nZ = static_cast<int>(zUnique.size());

        // 检查点数是否匹配
        if (nX * nY * nZ != nRows)
        {
            qDebug() << "错误：推断出的网格点数 " << nX * nY * nZ
                << " 与 table 行数 " << nRows << " 不一致！";
            return nullptr;
        }

        // 建立 x, y, z 值到对应索引的映射（方便后面找出每个点在标准排列中的位置）
        std::map<double, int> xIndexMap, yIndexMap, zIndexMap;
        for (int i = 0; i < nX; i++)
        {
            xIndexMap[xUnique[i]] = i;
        }
        for (int j = 0; j < nY; j++)
        {
            yIndexMap[yUnique[j]] = j;
        }
        for (int k = 0; k < nZ; k++)
        {
            zIndexMap[zUnique[k]] = k;
        }

        // 构造一个三维 mapping，mapping[k][j][i] 存储原来表格中对应点的行号
        std::vector<std::vector<std::vector<vtkIdType>>> indexMapping;
        indexMapping.resize(nZ, std::vector<std::vector<vtkIdType>>(nY, std::vector<vtkIdType>(nX, -1)));

        for (vtkIdType r = 0; r < nRows; r++)
        {
            double xVal = xArray->GetVariantValue(r).ToDouble();
            double yVal = yArray->GetVariantValue(r).ToDouble();
            double zVal = zArray->GetVariantValue(r).ToDouble();
            int i = xIndexMap[xVal];
            int j = yIndexMap[yVal];
            int k = zIndexMap[zVal];
            indexMapping[k][j][i] = r;
        }

        // 创建 vtkStructuredGrid 对象，并设置网格各维度
        vtkSmartPointer<vtkStructuredGrid> sgrid = vtkSmartPointer<vtkStructuredGrid>::New();
        sgrid->SetDimensions(nX, nY, nZ);

        vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
        points->SetNumberOfPoints(nRows);

        // 除前三列之外，其它列为场数据，创建对应的 vtkDoubleArray 数组
        int nCols = table->GetNumberOfColumns();
        std::vector<vtkSmartPointer<vtkDoubleArray>> fieldArrays;
        std::vector<std::string> fieldNames;
        for (int c = 3; c < nCols; c++)
        {
            vtkAbstractArray* origArr = table->GetColumn(c);
            vtkSmartPointer<vtkDoubleArray> newArr = vtkSmartPointer<vtkDoubleArray>::New();
            newArr->SetName(origArr->GetName());
            newArr->SetNumberOfTuples(nRows);
            fieldArrays.push_back(newArr);
            fieldNames.push_back(origArr->GetName());
        }

        // 按照 X 快速变化、Y 次之、Z 最慢的顺序遍历网格，填充点坐标和场数据
        vtkIdType ptId = 0;
        for (int k = 0; k < nZ; k++)
        {
            for (int j = 0; j < nY; j++)
            {
                for (int i = 0; i < nX; i++)
                {
                    vtkIdType rowIdx = indexMapping[k][j][i];
                    double xVal = xArray->GetVariantValue(rowIdx).ToDouble();
                    double yVal = yArray->GetVariantValue(rowIdx).ToDouble();
                    double zVal = zArray->GetVariantValue(rowIdx).ToDouble();
                    points->SetPoint(ptId, xVal, yVal, zVal);

                    // 同步复制每个点对应的场数据，保持顺序一致
                    for (size_t f = 0; f < fieldArrays.size(); f++)
                    {
                        vtkAbstractArray* origArr = table->GetColumnByName(fieldNames[f].c_str());
                        double fieldVal = origArr->GetVariantValue(rowIdx).ToDouble();
                        fieldArrays[f]->SetValue(ptId, fieldVal);
                    }
                    ptId++;
                }
            }
        }

        sgrid->SetPoints(points);
        for (auto& arr : fieldArrays)
        {
            QString first = QString(arr->GetName()).split("||").value(0).trimmed();
            arr->SetName(first.toUtf8().constData());
            sgrid->GetPointData()->AddArray(arr);
        }

        return sgrid;
    }

    void NearFieldDataGenerator::transformTableToStructuredGrid(vtkTable* inputTable,
        vtkStructuredGrid* outStructuredGrid, int xMax, int yMax, int zMax, bool reverseXYZ)
    {
        vtkNew<vtkTableToStructuredGrid> tableToSGFilter;
        tableToSGFilter->SetInputData(inputTable);
        if (reverseXYZ)
        {
            tableToSGFilter->SetXColumn(inputTable->GetColumn(2)->GetName());
            tableToSGFilter->SetYColumn(inputTable->GetColumn(1)->GetName());
            tableToSGFilter->SetZColumn(inputTable->GetColumn(0)->GetName());
            tableToSGFilter->SetWholeExtent(0, zMax, 0, yMax, 0, xMax);
        }
        else
        {
            tableToSGFilter->SetXColumn(inputTable->GetColumn(0)->GetName());
            tableToSGFilter->SetYColumn(inputTable->GetColumn(1)->GetName());
            tableToSGFilter->SetZColumn(inputTable->GetColumn(2)->GetName());
            tableToSGFilter->SetWholeExtent(0, xMax, 0, yMax, 0, zMax);
        }

        tableToSGFilter->Update();

        //vtkNew< vtkStructuredGridWriter> writer;
        //writer->SetInputConnection(tableToSGFilter->GetOutputPort());
        //writer->SetFileName("nearFieldStruc.vtk");
        //writer->Write();

        outStructuredGrid->DeepCopy(tableToSGFilter->GetOutput());
    }

    void NearFieldDataGenerator::logTheTable(vtkTable* inputTable,
        vtkTable* outputTable, double& logedMinimalValue, int realValueIndex)
    {
        //auto colsNum = inputTable->GetNumberOfColumns();
        outputTable->DeepCopy(inputTable);
        int couCount = outputTable->GetNumberOfColumns();
        if (realValueIndex < 0 || 3 + realValueIndex >= couCount)
        {
            qDebug() << "realValueIndex is out of range!";
            return;
        }
        auto valueArray = outputTable->GetColumn(3 + realValueIndex); //值列
        if (valueArray == nullptr)
        {
            return;
        }
        auto rowNum = valueArray->GetNumberOfTuples();
        for (int i = 0; i < rowNum; ++i)
        {
            auto value = valueArray->GetVariantValue(i).ToDouble();
            valueArray->SetVariantValue(i, m_logFactory * std::log10(value));
        }
    }

    void NearFieldDataGenerator::normalizeTheTable(vtkTable* inputTable,
        vtkTable* outputTable)
    {
        outputTable->DeepCopy(inputTable);

        int couCount = outputTable->GetNumberOfColumns();
        for (int i = 3; i < couCount; ++i)
        {
            auto valueArray = vtkDoubleArray::SafeDownCast(outputTable->GetColumn(i)); //值列
            if (valueArray == nullptr)
            {
                return;
            }

            vtkIdType nTuples = valueArray->GetNumberOfTuples();
            int nComp = valueArray->GetNumberOfComponents();
            double maxAbs = 0.0;//改为绝对值的最大值

            for (vtkIdType i = 0; i < nTuples; ++i)
            {
                for (int c = 0; c < nComp; ++c)
                {
                    double v = valueArray->GetComponent(i, c);
                    double av = std::abs(v);
                    if (av > maxAbs)
                    {
                        maxAbs = av;
                    }
                }
            }

            //auto maxValue = valueArray->GetValueRange()[1];

            auto rowNum = valueArray->GetNumberOfTuples();
            for (int i = 0; i < rowNum; ++i)
            {
                auto value = valueArray->GetVariantValue(i).ToDouble();
                valueArray->SetVariantValue(i, value / maxAbs);
            }
        }
    }

    QList<QList<double>> NearFieldDataGenerator::computeTableExtends(vtkTable* inputTable)
    {
        //if (m_originalTable == nullptr)
        //{
        //    return;
        //}
        QList<QList<double>> sliceEnums;

        vtkIdType numberOfColumns = inputTable->GetNumberOfColumns();
        if (numberOfColumns < 3)
        {
            return sliceEnums;
        }

        for (vtkIdType col = 0; col < numberOfColumns; ++col)
        {
            if (col < 3)
            {
                sliceEnums.append(QList<double>());
            }
            vtkDataArray* columnData = vtkDataArray::SafeDownCast(inputTable->GetColumn(col));

            if (columnData && columnData->GetNumberOfValues() > 0)
            {
                for (vtkIdType row = 0; row < columnData->GetNumberOfValues(); ++row)
                {
                    double value = columnData->GetComponent(row, 0);
                    if (col < 3)
                    {
                        auto& singleSlice = sliceEnums[col];
                        if (!singleSlice.contains(value))
                        {
                            singleSlice.append(value);
                        }
                    }
                }
                if (col < 3)
                {
                    //qDebug() << "Column " << col << " has " << sliceEnums[col].size() << " unique values.";
                }
            }
            else
            {
                qDebug() << "Column " << col << " has no data.";
            }
        }
        return sliceEnums;
    }

    void NearFieldDataGenerator::extractDataFromTable(const vtkSmartPointer<vtkTable>& table,
        QList<double>& xList,
        QList<double>& yList,
        QList<double>& zList,
        QList<vtkSmartPointer<vtkTable>>& extractedXRows,
        QList<vtkSmartPointer<vtkTable>>& extractedYRows,
        QList<vtkSmartPointer<vtkTable>>& extractedZRows)
    {
        if (!table) return;

        int numRows = table->GetNumberOfRows();
        int numCols = table->GetNumberOfColumns();

        // 限制至前三列  
        int colLimit = (numCols < 3) ? numCols : 3;

        //提取单位
        xSlicePositionUnit = TextArrayMetaHander::getUnitFromArray(table->GetColumn(0));
        ySlicePositionUnit = TextArrayMetaHander::getUnitFromArray(table->GetColumn(1));
        zSlicePositionUnit = TextArrayMetaHander::getUnitFromArray(table->GetColumn(2));

        // 使用 QSet 提取唯一值  
        QSet<double> uniqueX, uniqueY, uniqueZ;

        // Step 1: 提取每一列的唯一值  
        for (int row = 0; row < numRows; ++row)
        {
            if (colLimit > 0)
            {
                vtkVariant xValue = table->GetValue(row, 0); // 第一列 x  
                if (xValue.IsNumeric())
                {
                    uniqueX.insert(xValue.ToDouble());
                }
            }
            if (colLimit > 1)
            {
                vtkVariant yValue = table->GetValue(row, 1); // 第二列 y  
                if (yValue.IsNumeric())
                {
                    uniqueY.insert(yValue.ToDouble());
                }
            }
            if (colLimit > 2)
            {
                vtkVariant zValue = table->GetValue(row, 2); // 第三列 z  
                if (zValue.IsNumeric())
                {
                    uniqueZ.insert(zValue.ToDouble());
                }
            }
        }

        // 将唯一值存储到相应的QList中  
        xList.append(uniqueX.values());
        yList.append(uniqueY.values());
        zList.append(uniqueZ.values());
        std::sort(xList.begin(), xList.end()); // 对X列唯一值排序  
        std::sort(yList.begin(), yList.end()); // 对Y列唯一值排序  
        std::sort(zList.begin(), zList.end()); // 对Z列唯一值排序  

        //qDebug() << "xList = " << xList;
        //qDebug() << "yList = " << yList;
        //qDebug() << "zList = " << zList;

        //生成空表
        //QHash<double, vtkSmartPointer<vtkTable>> m_xTableHash, m_yTableHash, m_zTableHash;
        vtkNew<vtkTable> tempTable;
        tempTable->GetFieldData()->DeepCopy(table->GetFieldData());
        for (int i = 0; i < numCols; ++i)
        {
            auto columnName = table->GetColumnName(i);
            vtkNew<vtkDoubleArray> arr;
            arr->SetName(columnName);
            tempTable->AddColumn(arr);

            //复制元数据
            auto oldArray = table->GetColumn(i);
            TextArrayMetaStruct meta;
            TextArrayMetaHander::getArrayMeta(oldArray,meta);
            TextArrayMetaHander::setArrayMeta(arr, meta);
        }

        for (auto i : xList)
        {
            vtkNew<vtkTable> table;
            table->DeepCopy(tempTable);
            extractedXRows.append(table);
        }
        for (auto i : yList)
        {
            vtkNew<vtkTable> table;
            table->DeepCopy(tempTable);
            extractedYRows.append(table);
        }
        for (auto i : zList)
        {
            vtkNew<vtkTable> table;
            table->DeepCopy(tempTable);
            extractedZRows.append(table);
        }

        // 分表，提取数据
        for (int i = 0; i < numRows; ++i)
        {
            auto row = table->GetRow(i);
            auto currentX = row->GetValue(0).ToDouble();
            auto currentY = row->GetValue(1).ToDouble();
            auto currentZ = row->GetValue(2).ToDouble();

            if (xList.contains(currentX))
            {
                auto index = xList.indexOf(currentX);
                extractedXRows[index]->InsertNextRow(row);
            }
            if (yList.contains(currentY))
            {
                auto index = yList.indexOf(currentY);
                extractedYRows[index]->InsertNextRow(row);
            }
            if (zList.contains(currentZ))
            {
                auto index = zList.indexOf(currentZ);
                extractedZRows[index]->InsertNextRow(row);
            }
        }

        ////写出每个表到本地
        //for ( int i=0;i<extractedXRows.size();i++)
        //{
        //    double x = xList.at(i);
        //    auto fileName = QString("D:/expandedTable/X"+QString::number(x)+".csv");
        //    vtkNew<vtkDelimitedTextWriter> writer;
        //    writer->SetFileName(fileName.toStdString().c_str());
        //    writer->SetInputData(extractedXRows[i]);
        //    writer->Write();
        //}

        //for (int i = 0; i < extractedYRows.size(); i++)
        //{
        //    double y = yList.at(i);
        //    auto fileName = QString("D:/expandedTable/Y" + QString::number(y) + ".csv");
        //    vtkNew<vtkDelimitedTextWriter> writer;
        //    writer->SetFileName(fileName.toStdString().c_str());
        //    writer->SetInputData(extractedYRows[i]);
        //    writer->Write();
        //}

        //for (int i = 0; i < extractedZRows.size(); i++)
        //{
        //    double z = zList.at(i);
        //    auto fileName = QString("D:/expandedTable/Z" + QString::number(z) + ".csv");
        //    vtkNew<vtkDelimitedTextWriter> writer;
        //    writer->SetFileName(fileName.toStdString().c_str());
        //    writer->SetInputData(extractedZRows[i]);
        //    writer->Write();
        //}
    }

    vtkTable* NearFieldDataGenerator::extractTable(bool& isOk)
    {
        switch (m_sliceAxis)
        {
        case -1:
        {
            isOk = true;
            return m_originalTable;
        }
        case 0:
        {
            if (m_sliceValueIndex >= m_xList.size())
            {
                isOk = false;
                return nullptr;
            }

            isOk = true;
            return m_extractedXTables[m_sliceValueIndex];
        }
        case 1:
        {
            if (m_sliceValueIndex >= m_yList.size())
            {
                isOk = false;
                return nullptr;
            }

            isOk = true;
            return m_extractedYTables[m_sliceValueIndex];
        }
        case 2:
        {
            if (m_sliceValueIndex >= m_zList.size())
            {
                isOk = false;
                return nullptr;
            }

            isOk = true;
            return m_extractedZTables[m_sliceValueIndex];
        }
        }
        return nullptr;
    }

    void NearFieldDataGenerator::decideLogCoefficients()
    {
        //增益（7）人体吸收比（13）功率（16）方向性系数（17）雷达散射截面（18）
        QList<int> log10TypeList{ 7, 13, 16, 17, 18 };
        if (log10TypeList.contains(m_fileDealType))
        {
            m_logFactory = 10;
        }
        else
        {
            m_logFactory = 20;
        }
    }

    bool NearFieldDataGenerator::convertKeyColumnsUnitToMM(vtkTable* inputTable)
    {
        if (inputTable == nullptr || inputTable->GetNumberOfColumns() < 3)
        {
            return false;
        }

        vtkDoubleArray* xArray = vtkDoubleArray::SafeDownCast(inputTable->GetColumn(0));
        vtkDoubleArray* yArray = vtkDoubleArray::SafeDownCast(inputTable->GetColumn(1));
        vtkDoubleArray* zArray = vtkDoubleArray::SafeDownCast(inputTable->GetColumn(2));

        TextArrayMetaStruct metaStructX;
        TextArrayMetaStruct metaStructY;
        TextArrayMetaStruct metaStructZ;

        auto hasX = TextArrayMetaHander::getArrayMeta(xArray, metaStructX);
        auto hasY = TextArrayMetaHander::getArrayMeta(xArray, metaStructY);
        auto hasZ = TextArrayMetaHander::getArrayMeta(xArray, metaStructZ);

        if (!hasX || !hasY || !hasZ)
        {
            return false;
        }

        auto xUnit = metaStructX.unit.toLower();
        auto yUnit = metaStructY.unit.toLower();
        auto zUnit = metaStructZ.unit.toLower();

        if (xUnit != "mm")
        {
            for (vtkIdType i = 0; i < xArray->GetNumberOfTuples(); ++i)
            {
                double value = xArray->GetValue(i);
                UnitConversionToMM(xUnit, value);
                xArray->SetValue(i, value); // 转换为毫米
            }
        }

        if (yUnit != "mm")
        {
            for (vtkIdType i = 0; i < yArray->GetNumberOfTuples(); ++i)
            {
                double value = yArray->GetValue(i);
                UnitConversionToMM(yUnit, value);
                yArray->SetValue(i, value); // 转换为毫米
            }
        }

        if (zUnit != "mm")
        {
            for (vtkIdType i = 0; i < zArray->GetNumberOfTuples(); ++i)
            {
                double value = zArray->GetValue(i);
                UnitConversionToMM(zUnit, value);
                zArray->SetValue(i, value); // 转换为毫米
            }
        }

        return true;
    }

    void NearFieldDataGenerator::UnitConversionToMM(const QString& unit, double& value)
    {
        if (unit == "km")
        {
            value /= 1E-6;
        }
        else if (unit == "m")
        {
            value /= 1E-3;
        }
        else if (unit == "cm")
        {
            value /= 1E-1;
        }
        else if (unit == "mm")
        {
            value /= 1;
        }
        else if (unit == "um")
        {
            value /= 1E3;
        }
    }

    void NearFieldDataGenerator::setFileDealType(int type)
    {
        m_fileDealType = type;
    }

    int NearFieldDataGenerator::getFileDealType()
    {
        return m_fileDealType;
    }
}
